import {
  BadRequestException,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { UpdateFilmListDto } from './dto/update-film-list.dto';
import { CreateFilmListDto } from './dto/create-film-list.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { FilmList } from './entities/film-list.entity';
import { Repository } from 'typeorm';
import { AudioService } from 'src/audio/audio.service';
import { TextService } from 'src/text/text.service';
import { VideoService } from 'src/video/video.service';
import { PictureService } from 'src/picture/picture.service';
import { PathItemRelational } from 'src/path-item-relational/entities/path-item-relational.entity';
import { PathListService } from 'src/path-list/path-list.service';
import { FilmFileRelationalService } from 'src/film_file_relational/film_file_relational.service';
import { FilmPathRelationalService } from 'src/film_path_relational/film_path_relational.service';
import { UpdateGrouptofilmDto } from './dto/update-grouptofilm.dto';
import { CreateGrouptofilmDto } from './dto/create-grouptofilm.dto';
import { GroupToFilm } from './entities/grouptofilm.entity';
import { User } from 'src/user/entities/user.entity';
import { usertogroup } from 'src/group/entities/usertogroup.entity';

@Injectable()
export class FilmListService {
  constructor(
    @InjectRepository(FilmList)
    private readonly filmListRepository: Repository<FilmList>,
    @InjectRepository(GroupToFilm)
    private readonly groupToFilmRepository: Repository<GroupToFilm>,
    @InjectRepository(PathItemRelational)
    private readonly pathItemRelationalRepository: Repository<PathItemRelational>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(usertogroup)
    private readonly usertogroupRepository: Repository<usertogroup>,
    private readonly audioService: AudioService,
    private readonly textService: TextService,
    private readonly videoService: VideoService,
    private readonly pictureService: PictureService,
    private readonly pathListService: PathListService,
    private readonly filmFileRelationalService: FilmFileRelationalService,
    private readonly filmPathRelationalService: FilmPathRelationalService,
  ) {}

  async createFilm(createFilmListDto: CreateFilmListDto) {
    const insertRes = await this.filmListRepository.insert(
      this.filmListRepository.create(createFilmListDto),
    );
    return insertRes.raw[0].id;
  }
  getAllFilms() {
    return this.filmListRepository.find();
  }
  getFilmItemById(id: string) {
    return this.filmListRepository.findOne({
      where: { id: id },
    });
  }
  async checkFilmById(id: string) {
    const res = await this.getFilmItemById(id);
    if (res === null) {
      return false;
    } else {
      return true;
    }
  }
  getAllFilmItemByUser(email: any) {
    return this.filmListRepository.find({
      where: { creator: email },
    });
  }
  async updateFilmById(id: string, updateFilmListDto: UpdateFilmListDto) {
    const oldFolder = await this.filmListRepository.findOne({
      where: { id: id },
    });
    if (!oldFolder) {
      return '未找到匹配的记录，没有进行更新操作';
    }
    try {
      const updateFolder = this.filmListRepository.merge(
        oldFolder,
        updateFilmListDto,
      );
      await this.filmListRepository.save(updateFolder);
      return '修改剪辑项目属性成功!';
    } catch (err) {
      throw new BadRequestException('更新剪辑项目属性失败');
    }
  }

  async getPathByPathIdsByFilmId(film_id: string) {
    const pathList = await this.filmPathRelationalService.findByFilmId(film_id);
    if (pathList.length === 0) return [];
    const pathIdList = pathList.map((item) => item.path_id);
    const pathListResult =
      await this.pathListService.getPathByPathIds(pathIdList);
    return pathListResult;
  }
  async getByPathId(path_id: string): Promise<PathItemRelational[]> {
    return this.pathItemRelationalRepository.find({
      where: { path_id: path_id },
      select: ['item_id', 'type'],
    });
  }
  async findItemsByFilmIdToPath(filmId: string) {
    const pathList = await this.filmPathRelationalService.findByFilmId(filmId);
    const promises = pathList.map(async (pathItem) => {
      return await this.getByPathId(pathItem.path_id);
    });

    const tempArray = await Promise.all(promises);
    const result = await Promise.all(
      tempArray.map(async (subArray) => {
        return await Promise.all(
          subArray.map(async (item) => {
            let updatedItem;
            switch (item.type) {
              case 'Picture':
                updatedItem = await this.pictureService.findOne(item.item_id);
                break;
              case 'Video':
                updatedItem = await this.videoService.findOne(item.item_id);
                break;
              case 'Audio':
                updatedItem = await this.audioService.findOne(item.item_id);
                break;
              case 'Text':
                updatedItem = await this.textService.findOne(item.item_id);
                break;
            }
            updatedItem.itemType = item.type;
            return updatedItem;
          }),
        );
      }),
    );
    return result;
  }
  async removeFilmById(id: string) {
    // 删除item path 相关信息
    const res = await this.getPathByPathIdsByFilmId(id);
    res.forEach(async (pathItem) => {
      await this.filmPathRelationalService.deleteRelationByFilmIdByPathId(
        pathItem.id,
        id,
      );
      this.pathListService.remove(pathItem.id);
    });
    const resItem = await this.findItemsByFilmIdToPath(id);
    resItem.forEach(async (item: any) => {
      await this.pathItemRelationalRepository.delete({ item_id: item.id });
      switch (item.itemType) {
        case 'Picture':
          await this.pictureService.remove(item.id);
          break;
        case 'Video':
          await this.videoService.remove(item.id);
          break;
        case 'Audio':
          await this.audioService.remove(item.id);
          break;
        case 'Text':
          await this.textService.remove(item.id);
          break;
      }
    });
    await this.filmFileRelationalService.removeByFilmId(id);
    // 删除项目
    try {
      return this.filmListRepository.delete({ id: id });
    } catch (error) {
      return `删除失败`;
    }
  }
  async isFilmItemExist(filmId: string) {
    try {
      await this.filmListRepository.findOne({
        where: { id: filmId },
      });
      return true;
    } catch {
      return false;
    }
  }
  getAllPubilcFilmItem() {
    return this.filmListRepository.find({
      where: { film_type: 'public' },
    });
  }

  // 创建 小组和视频之间的关系
  async createFilmItemToGroup(
    createFilmListDto: CreateFilmListDto,
    groupuuid: string,
  ) {
    const filmuuid = await this.createFilm(createFilmListDto);
    const createGrouptofilmDto = new CreateGrouptofilmDto();
    createGrouptofilmDto.belong = createFilmListDto.creator;
    createGrouptofilmDto.filmuuid = filmuuid;
    createGrouptofilmDto.groupuuid = groupuuid;
    const groupToFilm = this.groupToFilmRepository.create(createGrouptofilmDto);
    this.groupToFilmRepository.insert(groupToFilm);
    return filmuuid;
  }
  getGroupToFilmItem(filmId: string) {
    return this.groupToFilmRepository.findOne({
      where: { filmuuid: filmId },
    });
  }
  async updateFilmItemToGroup(
    filmId: string,
    updateGrouptofilmDto: UpdateGrouptofilmDto,
  ) {
    const oldItem = await this.groupToFilmRepository.findOne({
      where: { filmuuid: filmId },
    });
    if (!oldItem) {
      return '该记录不存在';
    }
    try {
      const updateItem = this.groupToFilmRepository.merge(
        oldItem,
        updateGrouptofilmDto,
      );
      await this.groupToFilmRepository.save(updateItem);
      return '修改记录成功!';
    } catch (err) {
      throw '更新记录失败';
    }
  }
  async getFilmItemByGroupuuid(groupuuid: string) {
    const filmItemList = await this.groupToFilmRepository.find({
      where: { groupuuid: groupuuid },
    });
    const filmItemOfGroupList = await Promise.all(
      filmItemList.map(async (item) => {
        const filmInfo = await this.filmListRepository.find({
          where: { id: item.filmuuid },
        });
        if (filmInfo.length !== 0) {
          const userItem = await this.userRepository.findOne({
            where: { email: item.belong },
          });

          const usertogroupItem = await this.usertogroupRepository.findOne({
            where: { useruuid: userItem.id, groupuuid: groupuuid },
          });

          (filmInfo[0] as any).creator_nickname = usertogroupItem.groupnickname;
          (filmInfo[0] as any).scenceToGroupId = item.id;
        }

        return filmInfo[0];
      }),
    );
    return filmItemOfGroupList;
  }
  async deleteFilmItemFromGroup(filmToGroupId: string) {
    try {
      //删除原本信息
      const scenceTogroupInfo = await this.groupToFilmRepository.findOne({
        where: { id: filmToGroupId },
      });
      await this.removeFilmById(scenceTogroupInfo.filmuuid);
      return this.groupToFilmRepository.delete({
        id: filmToGroupId,
      });
    } catch (err) {
      console.error('删除记录失败', err);
      throw '删除记录失败';
    }
  }
}
